import 'dart:convert';
import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 配置类，用于表示单个配置
class Configuration {
  String id;
  String name;
  bool isDark;
  AccentColor color;
  String workspaceDir;
  String outputDir;
  
  Configuration({
    required this.id,
    required this.name,
    required this.isDark,
    required this.color,
    required this.workspaceDir,
    required this.outputDir,
  });
  
  // 从JSON创建配置对象
  factory Configuration.fromJson(Map<String, dynamic> json) {
    return Configuration(
      id: json['id'],
      name: json['name'],
      isDark: json['isDark'] ?? false,
      color: _stringToAccentColor(json['color']),
      workspaceDir: json['workspaceDir'] ?? '',
      outputDir: json['outputDir'] ?? '',
    );
  }
  
  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'isDark': isDark,
      'color': color.toString(),
      'workspaceDir': workspaceDir,
      'outputDir': outputDir,
    };
  }
  
  // 将字符串转换为AccentColor
  static AccentColor _stringToAccentColor(String? colorStr) {
    var accentColors = Colors.accentColors;
    for(var color in accentColors) {
      if(colorStr == color.toString()){
        return color;
      }
    }
    return Colors.blue;
  }
}

class ConfigController extends GetxController {
  static ConfigController get to => Get.find();
  
  late SharedPreferences _prefs;
  
  // 当前活跃的配置
  final _currentConfig = Rxn<Configuration>();
  
  // 所有配置列表
  final _configurations = <Configuration>[].obs;
  
  // 当前使用的配置ID
  final _activeConfigId = ''.obs;
  
  // Getter for reactive access
  Rxn<Configuration> get currentConfig => _currentConfig;
  List<Configuration> get configurations => _configurations;
  String get activeConfigId => _activeConfigId.value;
  
  @override
  void onInit() {
    super.onInit();
    _initPrefs();
  }
  
  Future<void> _initPrefs() async {
    _prefs = await SharedPreferences.getInstance();
    
    // 加载配置列表
    _loadConfigurations();
    
    // 加载当前活跃配置ID
    _activeConfigId.value = _prefs.getString('activeConfigId') ?? '';
    
    // 兼容旧配置
    if (_configurations.isEmpty) {
      _migrateFromOldConfig();
    }
    
    // 设置当前活跃配置
    if (_activeConfigId.value.isNotEmpty) {
      _currentConfig.value = _configurations.firstWhere(
        (config) => config.id == _activeConfigId.value,
        orElse: () => _getDefaultConfiguration(),
      );
    } else if (_configurations.isNotEmpty) {
      _currentConfig.value = _configurations.first;
      _activeConfigId.value = _currentConfig.value!.id;
      _prefs.setString('activeConfigId', _activeConfigId.value);
    } else {
      _currentConfig.value = _getDefaultConfiguration();
      _configurations.add(_currentConfig.value!);
      _activeConfigId.value = _currentConfig.value!.id;
      _saveConfigurations();
      _prefs.setString('activeConfigId', _activeConfigId.value);
    }
  }
  
  // 从旧配置迁移
  void _migrateFromOldConfig() {
    bool oldIsDark = _prefs.getBool('isDark') ?? false;
    AccentColor oldColor = _stringToAccentColor(_prefs.getString("color")) ?? Colors.blue;
    String oldWorkspaceDir = _prefs.getString("workspaceDir") ?? "";
    String oldOutputDir = _prefs.getString("outputDir") ?? "";
    
    // 尝试从旧的config字段获取配置
    final configString = _prefs.getString('config');
    if (configString != null) {
      final config = jsonDecode(configString);
      if(config['workspaceDir'] != null && oldWorkspaceDir == ""){
        oldWorkspaceDir = config['workspaceDir'] ?? "";
      }
    }
    
    // 如果工作空间为空，设置默认值
    if (oldWorkspaceDir.isEmpty) {
      String mainPath = Platform.resolvedExecutable;
      mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
      String defaultWorkspaceDir = "$mainPath${Platform.pathSeparator}workspace";
      
      Directory defaultWorkspace = Directory(defaultWorkspaceDir);
      if(!defaultWorkspace.existsSync()){
        defaultWorkspace.createSync();
      }
      oldWorkspaceDir = defaultWorkspaceDir;
    }
    
    // 如果输出目录为空，设置默认值
    if (oldOutputDir.isEmpty) {
      String mainPath = Platform.resolvedExecutable;
      mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
      String defaultOutputDirPath = "$mainPath${Platform.pathSeparator}output";
      
      Directory defaultOutputDir = Directory(defaultOutputDirPath);
      if(!defaultOutputDir.existsSync()){
        defaultOutputDir.createSync();
      }
      oldOutputDir = defaultOutputDirPath;
    }
    
    // 创建默认配置
    var defaultConfig = Configuration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: '默认配置',
      isDark: oldIsDark,
      color: oldColor,
      workspaceDir: oldWorkspaceDir,
      outputDir: oldOutputDir,
    );
    
    _configurations.add(defaultConfig);
    _currentConfig.value = defaultConfig;
    _activeConfigId.value = defaultConfig.id;
    
    _saveConfigurations();
    _prefs.setString('activeConfigId', _activeConfigId.value);
  }
  
  // 获取默认配置
  Configuration _getDefaultConfiguration() {
    String mainPath = Platform.resolvedExecutable;
    mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
    
    String defaultWorkspaceDir = "$mainPath${Platform.pathSeparator}workspace";
    Directory defaultWorkspace = Directory(defaultWorkspaceDir);
    if(!defaultWorkspace.existsSync()){
      defaultWorkspace.createSync();
    }
    
    String defaultOutputDirPath = "$mainPath${Platform.pathSeparator}output";
    Directory defaultOutputDir = Directory(defaultOutputDirPath);
    if(!defaultOutputDir.existsSync()){
      defaultOutputDir.createSync();
    }
    
    return Configuration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: '默认配置',
      isDark: false,
      color: Colors.blue,
      workspaceDir: defaultWorkspaceDir,
      outputDir: defaultOutputDirPath,
    );
  }
  
  // 加载配置列表
  void _loadConfigurations() {
    final configsJson = _prefs.getString('configurations');
    if (configsJson != null) {
      final List<dynamic> configsList = jsonDecode(configsJson);
      _configurations.assignAll(configsList.map((json) => Configuration.fromJson(json)));
    }
  }
  
  // 保存配置列表
  void _saveConfigurations() {
    final configsJson = jsonEncode(_configurations.map((config) => config.toJson()).toList());
    _prefs.setString('configurations', configsJson);
  }

  // 将字符串转换为AccentColor
  AccentColor _stringToAccentColor(String? color) {
    var accentColors = Colors.accentColors;
    for(var value in accentColors) {
      if(color == value.toString()){
        return value;
      }
    }
    return Colors.blue;
  }

  /**
   * 设置主题颜色
   */
  void setThemeColor(AccentColor color) {
    if (_currentConfig.value != null) {
      _currentConfig.value!.color = color;
      _saveConfigurations();
    }
  }

  void toggleTheme() {
    if (_currentConfig.value != null) {
      _currentConfig.value!.isDark = !_currentConfig.value!.isDark;
      _saveConfigurations();
    }
  }

  /**
   * 设置工作空间
   */
  void setWorkspaceDir(String workspace) {
    if (_currentConfig.value != null) {
      _currentConfig.value!.workspaceDir = workspace;
      _saveConfigurations();
    }
  }

  /**
   * 设置输出目录
   */
  void setOutputDir(String outputDir) {
    if (_currentConfig.value != null) {
      _currentConfig.value!.outputDir = outputDir;
      _saveConfigurations();
    }
  }
  
  /**
   * 创建新配置
   */
  void createConfiguration(String name, [Map<String, dynamic>? configData]) {
    // 确保配置名称唯一
    String uniqueName = name;
    int counter = 1;
    while (_configurations.any((config) => config.name == uniqueName)) {
      uniqueName = '$name ($counter)';
      counter++;
    }
    
    var newConfig = Configuration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: uniqueName,
      isDark: _currentConfig.value?.isDark ?? false,
      color: _currentConfig.value?.color ?? Colors.blue,
      workspaceDir: _currentConfig.value?.workspaceDir ?? '',
      outputDir: _currentConfig.value?.outputDir ?? '',
    );
    
    _configurations.add(newConfig);
    _saveConfigurations();
    
    // 如果提供了配置数据，保存它
    if (configData != null) {
      _saveConfigData(newConfig.id, configData);
    }
  }
  
  // 保存配置数据到SharedPreferences
  Future<void> _saveConfigData(String configId, Map<String, dynamic> configData) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('config_data_$configId', jsonEncode(configData));
  }
  
  /**
   * 删除配置
   */
  void deleteConfiguration(String configId) {
    if (configId == _activeConfigId.value) {
      // 不能删除当前活跃的配置
      return;
    }
    
    _configurations.removeWhere((config) => config.id == configId);
    _saveConfigurations();
  }
  
  /**
   * 切换配置 - 通过名称切换
   */
  void switchConfiguration(String configName) {
    final newConfig = getConfigByName(configName);
    if (newConfig != null && newConfig != _currentConfig.value) {
      _currentConfig.value = newConfig;
      _activeConfigId.value = newConfig.id;
      _prefs.setString('activeConfigId', _activeConfigId.value);
      
      // 打印日志以帮助调试
      print('已切换到配置: ${newConfig.name}, ID: ${newConfig.id}');
    }
  }
  
  /**
   * 获取当前活跃配置名称
   */
  String get activeConfigName => _currentConfig.value?.name ?? '';

  /**
   * 获取配置数据 - 通过名称
   */
  Future<Map<String, dynamic>?> getConfigData(String configName) async {
    final config = getConfigByName(configName);
    if (config != null) {
      final prefs = await SharedPreferences.getInstance();
      final configData = prefs.getString('config_data_${config.id}');
      if (configData != null) {
        return jsonDecode(configData);
      }
    }
    return null;
  }
  
  /**
   * 重命名配置
   */
  void renameConfiguration(String configId, String newName) {
    final configIndex = _configurations.indexWhere((config) => config.id == configId);
    if (configIndex != -1) {
      // 确保新名称唯一
      String uniqueName = newName;
      int counter = 1;
      while (_configurations.any((config) => config.id != configId && config.name == uniqueName)) {
        uniqueName = '$newName ($counter)';
        counter++;
      }
      
      _configurations[configIndex].name = uniqueName;
      _saveConfigurations();
    }
  }
  
  /**
   * 根据名称获取配置
   */
  Configuration? getConfigByName(String configName) {
    return _configurations.firstWhereOrNull((config) => config.name == configName);
  }
  
  /**
   * 保存配置到SharedPreferences（用于jar_place.dart的配置保存）
   */
  Future<void> saveConfigToPrefs(String configName, Map<String, dynamic> configData) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('config_$configName', jsonEncode(configData));
    
    // 确保GetX中存在该配置
    Configuration? existingConfig = getConfigByName(configName);
    if (existingConfig == null) {
      createConfiguration(configName, configData);
      existingConfig = getConfigByName(configName);
    } else {
      // 保存配置数据
      await _saveConfigData(existingConfig.id, configData);
    }
    
    // 切换到该配置
    if (existingConfig != null) {
      switchConfiguration(existingConfig.name);
    }
  }
  
  /**
   * 更新配置数据
   */
  Future<void> updateConfiguration(String configId, Map<String, dynamic> configData) async {
    await _saveConfigData(configId, configData);
  }
  
  /**
   * 从SharedPreferences加载配置（用于jar_place.dart的配置加载）
   */
  Future<Map<String, dynamic>?> loadConfigFromPrefs(String configName) async {
    final prefs = await SharedPreferences.getInstance();
    final configString = prefs.getString('config_$configName');
    
    if (configString != null) {
      // 确保GetX中存在该配置
      Configuration? existingConfig = getConfigByName(configName);
      if (existingConfig == null) {
        createConfiguration(configName);
        existingConfig = getConfigByName(configName);
      }
      
      // 切换到该配置
      if (existingConfig != null) {
        switchConfiguration(existingConfig.name);
      }
      
      return jsonDecode(configString);
    }
    
    return null;
  }
  
  /**
   * 获取所有配置名称（用于jar_place.dart的配置加载）
   */
  Future<List<String>> getConfigNames() async {
    final prefs = await SharedPreferences.getInstance();
    final keys = prefs.getKeys();
    final configNames = <String>[];
    
    for (var key in keys) {
      if (key.startsWith('config_') && key != 'configurations') {
        configNames.add(key.substring(7)); // 移除 'config_' 前缀
      }
    }
    
    return configNames;
  }
  
  /**
   * 删除配置（用于jar_place.dart的配置删除）
   */
  Future<void> deleteConfigFromPrefs(String configName) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('config_$configName');
    
    // 同时从GetX中删除
    Configuration? config = getConfigByName(configName);
    if (config != null) {
      deleteConfiguration(config.id);
    }
  }
}